<?php
/**
 * Created by PhpStorm.
 * User: Jessewang
 * Date: 2017/3/29
 * Time: 上午11:34
 */


namespace App\Libs;
use Swoole;
use Swoole\Client\CURL;
use Swoole\Client\Http;
class QqApi
{
    const OAUTH_PREFIX = 'https://graph.qq.com';
    const OAUTH_AUTHORIZE_URL = '/authorize?';
    const OAUTH_TOKEN_URL = '/sns/oauth2/access_token?';
    const OAUTH_REFRESH_URL = '/sns/oauth2/refresh_token?';
    const OAUTH_USERINFO_URL = '/user/get_user_info';
    const OAUTH_AUTH_URL = '/sns/auth?';

    public  $appid=null;
    public  $appkey = null;

    function  __construct()
    {
        $config = \Swoole::$php->config["sns"];

        $this->appid = $config['qq']['appid'];
        $this->appkey = $config['qq']['appkey'];
    }

    function  getUserInfo($accesstoken,$openid)
    {
        $httpClient = new CURL();
        $data = array(
            "access_token"=>$accesstoken,
            'openid'=>$openid,
            'oauth_consumer_key'=>$this->appid

        );
        $ret = $httpClient->get("https://graph.qq.com/user/get_user_info?".$this->buildQueryString($data));
	
        return json_decode($ret);
    }

    function buildQueryString($data)
    {
        $querystring = '';
        if (is_array($data)) {
            // Change data in to postable data
            foreach ($data as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $val2) {
                        $querystring .= urlencode($key) . '=' . urlencode($val2) . '&';
                    }
                } else {
                    $querystring .= urlencode($key) . '=' . urlencode($val) . '&';
                }
            }
            $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
        } else {
            $querystring = $data;
        }
        return $querystring;
    }
}
